#include "ClientSocketHandler.h"

ClientSocketHandler::ClientSocketHandler(int clientSocket) {
    this->_buffLength = 0;
    this->_currentReadPoint = 0;
    this->_clientSocket = clientSocket;
    this->_readSocket();
}

bool ClientSocketHandler::_readSocket() {
    // 从客户端接受length字节数据写入缓冲区，如果浏览器被叉掉程序会直接崩掉
    PrintLine("recv start");
    this->_buffLength = recv(this->_clientSocket, this->_buff, sizeof(this->_buff), MSG_NOSIGNAL); // 返回成功接收的数据长度（失败返回-1）
    PrintLine("recv finished [%d]", this->_buffLength);
    if(this->_buffLength < 0) {
        PrintLine("读取客户端请求数据失败");
        return false;
    }
    return true;
}

bool ClientSocketHandler::_writeSocket(const char* buff, int length) {
    // 把缓冲区数据发送给客户端，每次发送length字节，如果浏览器被叉掉程序会直接崩掉
    int ret = send(this->_clientSocket, buff, length, MSG_NOSIGNAL); // 返回成功发送的数据长度（失败返回-1）
    if(ret != length) {
        PrintLine("发送数据失败 [%d/%d]", ret, length);
        return false;
    }
    // todo：总感觉这里的ret和length不对劲，一直是[4096/4096]
    PrintLine("发送数据成功 [%d/%d]", ret, length);
    return true;
}

bool ClientSocketHandler::_getNextByte(char *c) {
    // 本轮数据读取完毕
    if(this->_currentReadPoint == this->_buffLength) {
        // 判断是否成功读取了，而不是傻傻地一股脑获取数据
        if(false == this->_readSocket()) {
            return false;
        }
        this->_currentReadPoint = 0;    // 归零
    }
    *c = this->_buff[this->_currentReadPoint++];
    return true;
}

ClientSocketHandler::~ClientSocketHandler() {
    close(this->_clientSocket);         // 关闭客户端套接字
}